package com.haidechizi.fastadmin.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.haidechizi.fastadmin.common.annotation.DataFilter;
import com.haidechizi.fastadmin.common.page.PageDto;
import com.haidechizi.fastadmin.modules.sys.dao.SysOfficeDao;
import com.haidechizi.fastadmin.modules.sys.entity.SysOffice;
import com.haidechizi.fastadmin.modules.sys.service.SysOfficeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class SysOfficeServiceImpl extends ServiceImpl<SysOfficeDao, SysOffice> implements SysOfficeService {

    @Override
    @DataFilter(subOffice = true, user = false)
    public List<SysOffice> queryList(PageDto pageDto, SysOffice sysOffice) {
        List<SysOffice> officeList =
                this.selectList(new EntityWrapper<SysOffice>()
                        .addFilterIfNeed(pageDto.getSqlFilter() != null, pageDto.getSqlFilter()));

        for (SysOffice office : officeList) {
            SysOffice parentOfficeEntity = this.selectById(office.getParentId());
            if (parentOfficeEntity != null) {
                office.setParentName(parentOfficeEntity.getName());
            }
        }
        return officeList;
    }

    @Override
    public List<Long> queryOfficeIdList(Long parentId) {
        return baseMapper.queryDetpIdList(parentId);
    }

    @Override
    public List<Long> getSubOfficeIdList(Long officeId) {
        //部门及子部门ID列表
        List<Long> officeIdList = new ArrayList<>();

        //获取子部门ID
        List<Long> subIdList = queryOfficeIdList(officeId);
        getOfficeTreeList(subIdList, officeIdList);

        return officeIdList;
    }

    /**
     * 获取部门名称
     *
     * @param officeId
     */
    @Override
    public String getOfficeName(Long officeId) {
        SysOffice sysOffice = this.selectById(officeId);
        if(sysOffice != null) {
            return sysOffice.getName();
        }
        return null;
    }

    /**
     * 递归
     */
    private void getOfficeTreeList(List<Long> subIdList, List<Long> officeIdList) {
        for (Long officeId : subIdList) {
            List<Long> list = queryOfficeIdList(officeId);
            if (list.size() > 0) {
                getOfficeTreeList(list, officeIdList);
            }

            officeIdList.add(officeId);
        }
    }
}
